package com.neuedu.mvc;

import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * 项目：      spring-framework
 * 类名:       FileController
 * 创建时间：  2024/3/21 15：42
 * 描述 :
 * 作者 :     张金山
 * QQ :     314649444
 * Site:      https://jshand.gitee.io
 */
@Controller
public class FileController {


    public static final String  UPLOAD_DIR = "D:\\upload";

    /**
     *  http://127.0.0.1:8080/mvc/test
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("test")
    String test(){
        return "success";
    }


    @RequestMapping("toupload")
    String toupload(){
        return "/upload.jsp";
    }


    @RequestMapping("upload_file")
    String uploadFile(MultipartFile myfile) throws IOException {


        String name = myfile.getName();
        String originalFilename = myfile.getOriginalFilename();
        long size = myfile.getSize();

        System.out.println("name = " + name);
        //  a.jpg   doc
        System.out.println("originalFilename = " + originalFilename);
        // jpg   doc
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
        System.out.println("size = " + size);

        //将文件从临时目录转出到  dist目标为止
        //D:\\upload\\唯一的xxxxx.jpg
        String uuid  =UUID.randomUUID().toString().replace("-","");
        String  newFileName =   uuid + ext;
        File dist = new File(UPLOAD_DIR,newFileName);
        myfile.transferTo(dist);


        return "redirect:/list_file";
    }


    /**
     * http://localhost:8080/mvc/list_file
     * @param model
     * @return
     */
    @RequestMapping("list_file")
    public String  listFile(Model model){


        File dir = new File(UPLOAD_DIR);
        File[] files = dir.listFiles();

        model.addAttribute("files",files);

        return "/file_list.jsp";
    }



    @RequestMapping("/download1")
    public void download( String filename , HttpServletResponse response) throws IOException {
        //设置头信息

//        MIME
//        attachment  有浏览器决定 是下载还是打开
//        inline  让浏览器直接打开（  如果不支持的类型，还是会提示下载）
        response.setContentType("application/ms-word");
        response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(filename,"utf-8"));


        //先从硬盘中读取流，
        //  a.jpg
        FileInputStream fis = new FileInputStream(new File(UPLOAD_DIR,filename));
        ServletOutputStream os = response.getOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while (     (len = fis.read(buffer))  != -1 ){
            //写入到浏览器
            os.write(buffer,0,len);
            os.flush();
        }

        os.close();
        fis.close();


    }


    @RequestMapping("/download2")
    public ResponseEntity download2( String filename ) throws IOException {



        File downFile = new File(UPLOAD_DIR,filename); //待下载的文件句柄

        ResponseEntity entity = ResponseEntity.ok().
                //mime
                        header(HttpHeaders.CONTENT_TYPE,"application/octet-stream").
                //通知浏览器以什么方式处理响应结果（直接打开，附件下载）
                        header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + URLEncoder.encode(filename,"utf-8") ).
                //设置body中为文件资源
                        body(new FileSystemResource(downFile));

        return  entity;

    }




}
